package project.sample.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author: WUZH009
 * @date: 2019/8/23 14:51
 **/
public class NettyHttpServer {

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workerGroup;
    private ServerBootstrap bootstrap;
    private int port;

    public NettyHttpServer(int port) {
        this.port = port;
        init();
    }

    private void init() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();


    }

    public void open() throws InterruptedException {
        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast("httpServerCodec", new HttpServerCodec())

//                                .addLast(new HttpResponseDecoder())
//                                .addLast(new HttpRequestEncoder())
                                .addLast(new HttpObjectAggregator(64 * 1024))
                                .addLast(new ChunkedWriteHandler())
                                .addLast("httpHandler", new HttpHandler());
                    }
                });
        bootstrap.bind(port).sync().channel().closeFuture().sync();
    }

    public static void main(String[] args) {
        try {
            new NettyHttpServer(8891).open();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
